package _10_binary_tree.getdepth;

import _10_binary_tree.TreeNode;
import org.junit.Test;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author: mornd
 * @dateTime: 2023/6/12 - 1:30
 * 求最小深度
 */
public class MinDepthTest {
    @Test
    public void test() {
//        TreeNode root = new TreeNode(1);
//        root.left = new TreeNode(2);
//        root.right = new TreeNode(3);
//        root.right.left = new TreeNode(4);

        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.left.left = new TreeNode(3);
        root.right = new TreeNode(4);
        root.right.right = new TreeNode(5);
        root.right.right.right = new TreeNode(6);

        System.out.println(minDepth(root));
        System.out.println(minDepth2(root) + "\n");
        System.out.println(root.printTreeStructure());
    }

    /**
     * 递归求最小深度
     * @param node
     * @return
     */
    int minDepth(TreeNode node) {
        if(node == null) {
            return 0;
        }
        int d1 = minDepth(node.left);
        int d2 = minDepth(node.right);
        if(d2 == 0) {
            return d1 + 1;
        }
        if(d1 == 0) {
            return d2 + 1;
        }
        return Math.min(d1, d2) + 1;
    }

    /**
     * 广度优先遍历实现
     * @param node
     * @return
     */
    int minDepth2(TreeNode node) {
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(node);
        int depth = 0;
        while (!queue.isEmpty()) {
            depth++;
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode poll = queue.poll();
                if(poll.left == null && poll.right == null) {
                    return depth;
                }
                if(poll.left != null) {
                    queue.offer(poll.left);
                }
                if(poll.right != null) {
                    queue.offer(poll.right);
                }
            }
        }
        return depth;
    }
}
